
package com.echo.sdk.im.handler;

import com.echo.sdk.im.constant.properties.CIMProperties;
import com.echo.sdk.im.model.CIMMsg;
import com.echo.sdk.im.model.CIMSession;
import com.echo.sdk.im.service.CIMSessionService;
import com.echo.sdk.im.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author chentl
 * @Version V1.0
 * @Project wh-bigdata-frame.
 * @Title AuthorizationHandler
 * @Description 账号绑定实现
 * @Package com.echo.sdk.im.server.handler
 * @Date 2021/6/18 2:31 下午
 */
@Component
public class AuthorizationHandler implements CIMRequestHandler {

    private final Logger logger = LoggerFactory.getLogger(AuthorizationHandler.class);

    @Resource
    private CIMSessionService cimSessionService;

    @Resource
    private CIMProperties cimProperties;

    @Override
    public void process(CIMSession newSession, CIMMsg cimMsg) {
        try {
            String userId = cimMsg.getUserId();

            if (StringUtils.isBlank(userId)) {
                logger.error("[server]用户id未知，禁止注册");
                return;
            }


            cimMsg.setNid(newSession.getNid());
            newSession.setUserId(userId);
            newSession.setBindTime(System.currentTimeMillis());
            newSession.setHost(cimProperties.getHost());
            newSession.setPort(cimProperties.getPort());
            newSession.setChannel(cimMsg.get("channel"));
            newSession.setDevice(cimMsg.get("device"));
            newSession.setAccount(cimMsg.getAccount());
            newSession.setOsVersion(cimMsg.get("osVersion"));

            //内部 session
            cimSessionService.save(cimMsg.getUserId(), newSession.getNid(), newSession);

            newSession.write(cimMsg);


        } catch (Exception exception) {
            logger.error("Authorize some errors occurred", exception);
        }

    }

}
